function [pX,pY,P2d,ODraw] = ProcessImage2DNW(hdfFilePath,autoROI,userROI,doFitData)

% [pX,pY,OD] = ProcessImage(hdfFilePath,autoROI,userROI,doFitData)
% Finds Gaussian-shaped signals on fluorescence or absorption images.
% Returns:
% pX - The parameters for a Gaussian fit to the data in the x (vertical)
% direction.
% pX(1) = Gaussian amplitude
% pX(2) = Peak position (in units of image pixels)
% pX(3) = Standard deviation (in units of image pixels)
% pX(4) = Offset
% pY - Same description as pX
% OD - The image (OD if it's an absorption image, raw image for a fluor.)
% num - Counts in raw "atoms" image, with electronic noise subtracted
% den - Counts in raw "background" image, with electronic noise subtracted.

close(figure(100))

% Inputs from hdf5 file
rawimages = cast(h5read(hdfFilePath,'/Image/image'),'double')/4;  %recasting from 2^14 to 2^16 bits
img_var = h5read(hdfFilePath,'/Image/configuration');
img_time = h5read(hdfFilePath,'/Image/exposuretime');
type_img = h5read(hdfFilePath,'/Image/typeimaging');
CCDbin = 1; % Amount of binning at camera sensor; '1' is 1x1 binning and '2' is 2x2 binning

%Software binning for 2D fits
bindim=[4,4];  % Software binning size

% Libraries used in this function
expp = ParamImgSys(img_var);
cons = Constants();

% Size of hdf5 image group
[rows,cols,files] = size(rawimages); % rows = horiz. pixels; cols = vert. pixels

ovflw = 'no';   % setting 'ovflw' flag to 'no'
if  type_img == 3 % Absorption
    elec = rawimages(:,:,3);
   %  num = rawimages(:,:,1) - elec;
   %  den = rawimages(:,:,2) - elec;
    num = rawimages(:,:,1);
    den = rawimages(:,:,2);
    maxcntN = max(max(num));
    maxcntD = max(max(den));
    if maxcntN > 2^16 || maxcntD > 2^16
        ovflw = 'yes';
        warning('Bin overflow warning');
    end
    
    %scaling the baselevel of the atom image
    numforscale=8;  %using a 10x10 pixel area to determine scaling fraction
    numleftup = sum(sum(num(1:numforscale,1:numforscale)));
    numleftdn = sum(sum(num(rows-numforscale:rows,1:numforscale)));
    numrightup = sum(sum(num(1:numforscale,cols-numforscale:cols)));
    numrightdn = sum(sum(num(rows-numforscale:rows,cols-numforscale:cols)));
    baselevelnum = numleftup + numleftdn + numrightup + numrightdn;
    
    denleftup = sum(sum(den(1:numforscale,1:numforscale)));
    denleftdn = sum(sum(den(rows-numforscale:rows,1:numforscale)));
    denrightup = sum(sum(den(1:numforscale,cols-numforscale:cols)));
    denrightdn = sum(sum(den(rows-numforscale:rows,cols-numforscale:cols)));
    baselevelden = denleftup + denleftdn + denrightup + denrightdn;
    blscale = (baselevelden/baselevelnum); %resulting baselevel scaling
    
    figure(200)
    subplot(2,2,1)
    surf(num,'Marker','.') %Plot filtered OD data
    cax=caxis;
    %colorbar
    shading flat
    grid off
    title('raw num')
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    max(max(num))
    
    subplot(2,2,2)
    surf(den,'Marker','.') %Plot filtered OD data
    caxis(cax)
    %colorbar
    shading flat
    grid off
    title('raw bg')
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    max(max(den))
    
    subplot(2,2,3)
    surf(elec,'Marker','.') %Plot filtered OD data
    %caxis(cax)
    %colorbar
    shading flat
    grid off
    title('elec')
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    max(max(elec))
    
    subplot(2,2,4)
    surf((num./den),'Marker','.') %Plot filtered OD data
    %caxis(cax)
    %colorbar
    shading flat
    grid off
    title('(num./den)')
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    min(min(num./den))
    
    modnum=num*blscale;
    ODraw = -log((num./den)');  % MATRIX ROTATED HERE
%      ODraw = -log((modnum./den)');
%      ODraw(isinf(ODraw)) = 0;
%      ODraw(isnan(ODraw)) = 0;
%      ODraw = real(ODraw);
     
elseif type_img == 1 % Fluorescence
    ODraw = rawimages';         % MATRIX ROTATED HERE
    ODraw = ODraw - min(min(ODraw));
else
    error('Can''t determine imaging method');
end

% Filter image to find ROI
N = 1;  %amplitude of 2D gaussian filter
sig = 10;  %size of 2D gaussian filter
ODfilt = conv2(ODraw,gaussian2d(N,sig),'same'); % Low-pass filter image

yC = 1:expp.short_px_nb;   %HORIZONTAL DIMENSION OF EXPERIMENT
xC = 1:expp.long_px_nb;

autoROIok = false;
if autoROI % Find ROI and extract first approx. signal from filtered image
    % Determine pre-ROI for fitting (for initial guesses)
    mx = max(max(ODfilt));
    [I,J] = find(ODfilt == mx,1);
    wndw = 50;
    if ~(I - wndw < 1 || I + wndw > max(xC) || J - wndw < 1 || J + wndw > max(yC))
        autoROIok = true;
        
        ROI(1) = I(1);
        ROI(2) = J(1);
        
        % INTEGRATED ODfilt in diff. dimens. using pre-ROI as size (for initial guesses)
        yIntFilt = sum(ODfilt(:,ROI(2)-wndw:ROI(2)+wndw),2);
        xIntFilt = sum(ODfilt(ROI(1)-wndw:ROI(1)+wndw,:),1);
        
        % Least-squares fit of INTEGRATED ODfilt (initial guesses)
        ampGuessY = max(yIntFilt) - min(yIntFilt);
        ampGuessX = max(xIntFilt) - min(xIntFilt);
        options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
        pYtmp = fminsearch(@(p)FitGauss(p,yC,yIntFilt),[ampGuessY ROI(1) 100 min(yIntFilt)],options);
        pXtmp = fminsearch(@(p)FitGauss(p,xC,xIntFilt'),[ampGuessX ROI(2) 100 min(xIntFilt)],options);
        
        % Determining autoROI based on size of ODfilt (for real fit)
        sigmas = 3;
        xWndw = round(sigmas*pXtmp(3));
        yWndw = round(sigmas*pYtmp(3));
        xROI = ROI(2)-xWndw:ROI(2)+xWndw;
        yROI = ROI(1)-yWndw:ROI(1)+yWndw;
        
        % Remove parts of the ROI if it goes outside of the photo.
        if min(xROI) < 1
            xROI = xROI(xROI > 0);
        end
        if min(yROI) < 1
            yROI = yROI(yROI > 0);
        end
        
        if max(yROI) > expp.short_px_nb
            yROI = yROI(yROI < expp.short_px_nb + 1);
        end
        if max(xROI) > expp.long_px_nb
            xROI = xROI(xROI < expp.long_px_nb + 1);
        end
        
        % INTEGRATED ODraw in diff. dimens. using autoROI as size (for real fit)
        yInt = sum(ODraw(yROI,xROI),2);
        xInt = sum(ODraw(yROI,xROI),1);
        
    else
        warndlg('Can''t auto-choose ROI: Estimated signal close to edge of image')
        autoROIok = false;
    end
end

if ~autoROIok  % Use user-input ROI parameters to get initial fitting parameters
    % User-defined ROI
    yROI = userROI(3):userROI(4);
    xROI = userROI(1):userROI(2);
    
    % INTEGRATED ODraw in diff. dimens. using autoROI as size (for real fit)
    yInt = sum(ODraw(yROI,xROI),2);
    xInt = sum(ODraw(yROI,xROI),1);
    
    % Amp. and sizes (initial guesses)
    pYtmp(1) = max(yInt) - min(yInt);
    pXtmp(1) = max(xInt) - min(xInt);
    pYtmp(2:3) = [mean(userROI(3:4)) 150];
    pXtmp(2:3) = [mean(userROI(1:2)) 150];
end

if doFitData % Real fit of ODraw using initial guesses
    options = optimset('Display','off','TolFun',1e-16,'TolX',1e-16);
    pY = fminsearch(@(p)FitGauss(p,yROI,yInt),[pYtmp(1:3) min(yInt)],options);
    pX = fminsearch(@(p)FitGauss(p,xROI,xInt'),[pXtmp(1:3) min(xInt)],options);
else
    pY = zeros(1,4);
    pX = pY;
end

if doFitData
    figure(100)
    subplot(2,3,1)
    surf(ODfilt,'Marker','.') %Plot filtered OD data
    cax=caxis;
    colorbar
    shading flat
    grid off
    title('Filtered ODraw')
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    
    % Binning ODraw for 2D fitting
    ODrawbin=BinImg2d(ODraw,bindim);  % NOTE - Rotated w/ respect to original image
    
    figure(100)
    subplot(2,3,4)
    surf(ODrawbin,'Marker','.') %Plot binned ODraw data
    cax=caxis;
    colorbar
    shading flat
    grid off
    title('Binned ODraw')
    view(0,90);
    xlabel('vert binned')
    ylabel('horiz binned')
    
    % Using ODrawbin for 2D fitting IC
    [horizbin,vertbin] = size(ODrawbin);  % y-dir. is HORIZ. exper. dir.; x-dir. is VERT
    amp2d=max(max(ODrawbin));
    [yoff2d,xoff2d] = find(ODrawbin == amp2d);
    sigx2d=vertbin/10;
    sigy2d=horizbin/10;
    guessave=3; %using a 3x3 binned pixel area to determine scaling fraction
    guessleftup = sum(sum(ODrawbin(1:guessave,1:guessave)))/guessave^2;
    guessleftdn = sum(sum(ODrawbin(horizbin-guessave:horizbin,1:guessave)))/guessave^2;
    guessrightup = sum(sum(ODrawbin(1:guessave,vertbin-guessave:vertbin)))/guessave^2;
    guessrightdn = sum(sum(ODrawbin(horizbin-guessave:horizbin,vertbin-guessave:vertbin)))/guessave^2;
    offset2d=(guessleftup + guessleftdn + guessrightup + guessrightdn)/4 ;
    slopex2d=((guessrightup + guessrightdn) - (guessleftup + guessleftdn))/(2*horizbin);
    slopey2d=((guessleftdn + guessrightdn) - (guessrightup + guessleftup))/(2*vertbin);
    IniCondNR=[offset2d,amp2d,xoff2d,yoff2d,sigx2d,sigy2d,slopex2d,slopey2d];
    
    % Creating matrices for 2D fitting with ODrawbin
    xvecbin=1:vertbin;
    yvecbin=1:horizbin;
    Nptsbin=vertbin*horizbin;
    [xdatabin,ydatabin]=meshgrid(xvecbin,yvecbin);  % xdata(ydata) have columns=length(xvec), rows=length(yvec)
    % xdata copies xvec along its rows; ydata copies yvec along its columns
    error2d(1:Nptsbin)=1;   % DUMMY
    npoints(1:Nptsbin)=1;   % DUMMY - Each entry is the number of points
    fitcoordmatrix=[xdatabin(:),ydatabin(:),error2d(:),npoints(:)];
    Z2dbin=ODrawbin(:);  %flattened(1D) vector of ODrawbin
    
    % Fitting - data is treated with equal weight
    opts=statset('TolFun',1e-6);
    [P2dbin,r2dbin,J2dbin]=nlinfit(fitcoordmatrix,Z2dbin(:),@gauss2derror,IniCondNR,opts);
    P2d = [P2dbin(1),P2dbin(2),P2dbin(3)*bindim(2),P2dbin(4)*bindim(1),P2dbin(5)*bindim(2),P2dbin(6)*bindim(1),P2dbin(7)/bindim(2),P2dbin(8)/bindim(1)];
    
    % Generate OD plot based on fit parameters
    [horiz,vert] = size(ODraw);  % y-dir. is HORIZ. exper. dir.; x-dir. is VERT
    xvec=1:vert;
    yvec=1:horiz;
    Npts=vert*horiz;
    [xdata,ydata]=meshgrid(xvec,yvec);
    ploterrorod(1:Npts)=1;
    plotnpoints(1:Npts)=1;
    plotcoordmatrix=[xdata(:),ydata(:),ploterrorod(:),plotnpoints(:)];
    
    ODcalcvec=gauss2derror(P2d,plotcoordmatrix);    %OD calculated from fit paramters
    ODcalc = reshape(ODcalcvec, size(xdata));
    
    ODcalcbinvec=gauss2derror(P2dbin,fitcoordmatrix);    %ODbin calculated from fit paramters
    ODcalcbin = reshape(ODcalcbinvec, size(xdatabin));
    
    ODcalcICvec=gauss2derror(IniCondNR,fitcoordmatrix);   %OD based on initial conditions
    ODcalcIC = reshape(ODcalcICvec, size(xdatabin));
    
    ODresiduals = ODfilt-ODcalc;
    
    subplot(2,3,5)
    surf(ODcalcIC,'Marker','.')  %Plot 2d fit using IC
    %caxis(cax)
    colorbar
    shading flat
    grid off
    view(0,90);
    xlabel('vert binned')
    ylabel('horiz binned')
    title('OD (binned) from initial conditions')
    hold on
    
    subplot(2,3,2)
    surf(ODcalc,'Marker','.')  %Plot 2d fit using fit param
    caxis(cax)
    colorbar
    shading flat
    grid off
    view(0,90);
    xlabel('vert')
    ylabel('horiz')
    title('OD from 2d fit')
    hold on
    
    
    subplot(2,3,6)
    surf(ODcalcbin,'Marker','.')  %Plot 2d fit using binned fit param
    caxis('auto')
    view(0,90);
    colorbar
    shading flat
    grid off
    title('OD (binned) from 2d fit param.')
    xlabel('vert binned')
    ylabel('horiz binned')
    hold off
    
    subplot(2,3,3)
    surf(ODresiduals,'Marker','.')  %Plot 2d fit residuals
    caxis('auto')
    view(0,90);
    colorbar
    shading flat
    grid off
    title('True residues (ODfilt-ODcalc)')
    xlabel('vert')
    ylabel('horiz')
    hold off
else
    P2d = [0,0,0,0,0,0,0,0];
end

% Give the width as the std deviation
widthYm1d = (pY(3))*expp.px_size*CCDbin/expp.mag;    %1D fits Y cloud size (m)
widthXm1d = (pX(3))*expp.px_size*CCDbin/expp.mag;    %1D fits X cloud size (m)
widthYm2d = (P2d(6))*expp.px_size*CCDbin/expp.mag;    %2D fits Y cloud size (m)
widthXm2d = (P2d(5))*expp.px_size*CCDbin/expp.mag;    %2D fits X cloud size (m)
amp = (pX(1) + pY(1))/2;                    % Mean of 1D Gaussian fits

if type_img == 1 % Fluorescence
    % Estimate number of atoms using camera
    total_num_electrons1d = amp*sqrt(2*pi)*mean([pX(3) pY(3)]);
    total_num_electrons2d = P2d(2)*2*pi*P2d(6)*P2d(5);
    total_photons1d = total_num_electrons1d/(expp.qe*expp.coll_eff);
    total_photons2d = total_num_electrons2d/(expp.qe*expp.coll_eff);
    num_atoms1d = 2*total_photons1d/(img_time*2*pi*cons.Gamma); % num_atoms = (num_photons/time) / (scattering rate)
    num_atoms2d = 2*total_photons2d/(img_time*2*pi*cons.Gamma); % num_atoms = (num_photons/time) / (scattering rate)
elseif type_img == 3 % Absorption
    totalODraw = sum(sum(ODraw))*(expp.px_size*CCDbin/expp.mag)^2;
    num_atomsOD = totalODraw/AbsCross(0,0);
    num_atomsFit = P2d(2)*2*pi*widthYm2d*widthXm2d/AbsCross(0,0);
end

if type_img == 1 % Fluorescence
    figure(1)
    subplot(3,3,[1 2 4 5])
    oneMat = ones(size(ODraw));
    zeroMat = nan(size(ODraw));
    zeroMat(yROI,xROI) = 1;
    ODwindow = ODraw.*zeroMat;
    imagesc(ODwindow);
    line([xROI(1) xROI(end)],[yROI(1) yROI(1)])
    line([xROI(1) xROI(1)],[yROI(1) yROI(end)])
    line([xROI(end) xROI(end)],[yROI(1) yROI(end)])
    line([xROI(1) xROI(end)],[yROI(end) yROI(end)])
    axis equal
    xlims = xlim;
    ylims = ylim;
    
    subplot(3,3,[3 6])
    plot(yInt,yROI,gauss(pY,yC),yC);
    set(gca,'YDir','reverse');
    ylim(ylims);
    
    subplot(3,3,[7 8])
    plot(xROI,xInt,xC,gauss(pX,xC));
    xlim(xlims);
    
    h = subplot(3,3,9,'Visible', 'off');
    cla(h);
    text(0, .5, sprintf('%s\n%s\n%s\n%s \n%s \n%s\n%s', ...
        ['v-width 1D (um): ' num2str(widthXm1d*cons.um)],['v-width 2D (um): ' num2str(widthXm2d*cons.um)],...
        ['h-width 1D (um): ' num2str(widthYm1d*cons.um)], ...
        ['h-width 2D (um): ' num2str(widthYm2d*cons.um)], ...
        ['peak 1D (v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')'],['Na (1D) = ' num2str(num_atoms1d,'%e')], ...
        ['Na (2D) = ' num2str(num_atoms2d,'%e')]), ...
        'VerticalAlignment', 'middle', ...
        'FontName', 'Courier New', ...
        'FontWeight', 'bold', ...
        'FontSize', 12);
elseif type_img == 3 % Absorption
    figure(1)
    subplot(4,3,[1 2 4 5 ])
    oneMat = ones(size(ODraw));
    zeroMat = nan(size(ODraw));
    zeroMat(yROI,xROI) = 1;
    ODwindow = ODraw.*zeroMat;
    imagesc(ODwindow);
    % imagesc((ODfilt));
    line([xROI(1) xROI(end)],[yROI(1) yROI(1)])
    line([xROI(1) xROI(1)],[yROI(1) yROI(end)])
    line([xROI(end) xROI(end)],[yROI(1) yROI(end)])
    line([xROI(1) xROI(end)],[yROI(end) yROI(end)])
    axis equal
    xlims = xlim;
    ylims = ylim;
    
    subplot(4,3,[3 6])
    plot(yInt,yROI,gauss(pY,yC),yC);
    set(gca,'YDir','reverse');
    ylim(ylims);
    
    subplot(4,3,[7 8])
    plot(xROI,xInt,xC,gauss(pX,xC));
    xlim(xlims);
    
    subplot(4,3,10)
    imagesc(num')
    axis equal
    
    subplot(4,3,11)
    imagesc(den')
    axis equal
    
    subplot(4,3,12)
    imagesc(elec')
    axis equal
    
    h = subplot(4,3,9,'Visible', 'off');
    cla(h);
    text(0, .6, sprintf('%s\n%s\n%s\n%s\n%s\n%s \n%s \n%s \n%s \n%s \n%s \n%s', ...
        ['v-width 2D (um): ' num2str(widthXm2d*cons.um)], ['h-width 2D (um): ' num2str(widthYm2d*cons.um)], ...
        ['v-width 1D (um): ' num2str(widthXm1d*cons.um)], ['h-width 1D (um): ' num2str(widthYm1d*cons.um)], ...
        ['peak 1D (v,h) = (' num2str(round(pX(2))) ',' num2str(round(pY(2))) ')'], ...
        ['peak ODraw at (v,h) = ' num2str(ODraw(round(pY(2)),round(pX(2))))], ...
        ['N(image) = ' num2str(num_atomsOD,'%e')], ...
        ['N(fit) = ' num2str(num_atomsFit,'%e')], ...
        ['peak pixel cnt on bg image = ' num2str(max(max(den)))], ...
        ['Peak OD(image) = ' num2str(max(max(ODraw)))], ...
        ['Peak OD(fit) = ' num2str(P2d(2))], ...
        ['Mean OD(image) = ' num2str(mean(mean(ODraw)))]), ...
        'VerticalAlignment', 'middle', ...
        'FontName', 'Courier New', ...
        'FontWeight', 'bold', ...
        'FontSize', 12);
end
[ODmax ximgmax]=max(max(ODraw))
[ODmaxck yimgmax]=max(ODraw(:,ximgmax))
% figure(200)
% subplot(1,2,1)
% surf(ODfilt,'Marker','.') %Plot filtered OD data
% cax=caxis;
% %colorbar
% shading flat
% grid off
% title('Filtered ODraw')
% view(0,90);
% xlabel('vert')
% ylabel('horiz')
%
% % Binning ODraw for 2D fitting
% ODrawbin=BinImg2d(ODraw,bindim);  % NOTE - Rotated w/ respect to original image
%
% subplot(1,2,2)
% surf(ODrawbin,'Marker','.') %Plot binned ODraw data
% cax=caxis;
% %colorbar
% shading flat
% grid off
% title('Binned ODraw')
% view(0,90);
% xlabel('vert binned')
% ylabel('horiz binned')